/*
 * Copyright (c) 2023, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "common_inc.h"

incremental_pid_t left_speed_pid;
incremental_pid_t right_speed_pid;

int16_t target_speed;

int main(void)
{
    SYSCFG_DL_init();
    debug_init();
    imu_init();
    openmv_init();
    oled_init();
    motor_init();
    encoder_init();
    while (nrf24l01_check()){
        printf("nrf24l01 not found\n");
        delay_ms(200);
    }
    nrf24l01_init();
    nrf24l01_set_rx_mode();
    timerA_init();
    timerB_init();

	incremental_pid_init(&left_speed_pid, 25.0f, 1.0f, 0, MAX_DUTY);
	incremental_pid_init(&right_speed_pid, 25.0f, 1.0f, 0, MAX_DUTY);
    uint8_t isRunning = 0;
    menu_init();

    while (1) {
        menu_task();
    }
}

// 10ms
void timerA_callback()
{
    encoder_callback();
    int16_t left_duty = (int16_t)incremental_pid(&left_speed_pid, left_speed, target_speed);
    int16_t right_duty = (int16_t)incremental_pid(&right_speed_pid, right_speed, target_speed);
    motor_set_duty(left_duty, right_duty);
//    vofa_add_data(left_speed);
//    vofa_add_data(right_speed);
//    vofa_add_data(target_speed);
//    vofa_send();
}

// 15ms
void timerB_callback()
{
//    printf("timerB\n");
}

void GROUP1_IRQHandler(void)
{
    encoder_exti_callback();
    nrf24l01_receive_callback();
}
